/********* Puzzle.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>

@interface Puzzle : CDVPlugin {
    // Member variables go here.
}

- (void)toPuzzle:(CDVInvokedUrlCommand*)command;
@end

@implementation Puzzle


- (void)toPuzzle:(CDVInvokedUrlCommand*)command {
    
    
    NSData *data1   = [[NSData alloc]initWithBase64EncodedString:[command argumentAtIndex:0] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSData *data2   = [[NSData alloc]initWithBase64EncodedString:[command argumentAtIndex:1] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    // NSData *data3   = [[NSData alloc]initWithBase64EncodedString:[command argumentAtIndex:2] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    UIImage *img1 = [UIImage imageWithData:data1];
    UIImage *img2 = [UIImage imageWithData:data2];
    // UIImage *img3 = [UIImage imageWithData:data3];
    
    CGImageRef img1Ref = img1.CGImage;
    CGImageRef img2Ref = img2.CGImage;
    // CGImageRef img3Ref = img3.CGImage;
    
    CGFloat w1 = CGImageGetWidth(img1Ref);
    
    CGFloat h1 = CGImageGetHeight(img1Ref);
    CGFloat h2 = CGImageGetHeight(img2Ref);
    // CGFloat h3 = CGImageGetHeight(img3Ref);
    // CGFloat hh= h1+h2+h3;
    CGFloat hh= h1;
    
    
    UIGraphicsBeginImageContext(CGSizeMake(w1,hh));
    [img1 drawInRect:CGRectMake(0, 0, w1, h1)];
    [img2 drawInRect:CGRectMake(0, h1-h2,w1, h2)];
    // [img3 drawInRect:CGRectMake(0, h1+h2, w1, h3)];
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData *_data = UIImageJPEGRepresentation(resultImg, 0.3f);
    NSString *_encodedImageStr =[_data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //    CGImageRelease(img1Ref);
    //    CGImageRelease(img2Ref);
    //    CGImageRelease(img3Ref);
    CDVPluginResult*  pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:_encodedImageStr];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

@end
